//
//  HomeViewController.swift
//  AgricultureApp
//
//  Created by eport_user1 on 2018/1/9.
//  Copyright © 2018年 eport_user1. All rights reserved.
//

import UIKit
import SnapKit
import PKHUD



class HomeViewController: BaseViewController,UITableViewDataSource,UITableViewDelegate {
    
    let iden1 = "iden1"
    let iden2 = "iden2"
    let iden3 = "iden3s"
 
    var tableView:UITableView?
    var mutaArray = [HomeModel]()
    
    var page:Int = 1
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        setupNav()
        setupTable()
        setupMJRefresh()
        loadData()
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

extension HomeViewController {
    
    func  setupNav() -> Void {
       
        title = "首页"
        view.backgroundColor = UIColor.white
        
        //导航栏左侧按钮
        let button = UIButton.init(type: .custom)
        button.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
        button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
        button.setImage(UIImage.init(named: "user_icon@2x.png"), for: .normal)
        let leftItem = UIBarButtonItem.init(customView: button)
        self.navigationItem.leftBarButtonItem = leftItem
        
        
    }
    
   @objc private func buttonAction(btn:UIButton) -> Void {
        
        print("do some things")
        
    }
    
    
    func setupTable() -> Void {
       
        tableView = UITableView.init(frame:CGRect.init(x: 0, y: 0, width: 0, height: 0), style: .plain)
        tableView?.frame = CGRect()
        tableView?.delegate = self
        tableView?.dataSource = self
        view.addSubview(tableView!)
        tableView?.tableFooterView = UIView()
        tableView?.backgroundColor = UIColor.gray
        tableView?.snp.makeConstraints({ (make) in
            
            make.edges.equalTo(view)
        })
        
        //注册单元格
        self.tableView?.register(UINib.init(nibName: "ShowCell1", bundle: nil), forCellReuseIdentifier: iden1)
        
         self.tableView?.register(UINib.init(nibName: "ShowCell2", bundle: nil), forCellReuseIdentifier: iden2)
        
         self.tableView?.register(UINib.init(nibName: "ShowCell3", bundle: nil), forCellReuseIdentifier: iden3)

    }
    
    
    
}

extension HomeViewController{
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        
        let cell1 = tableView.dequeueReusableCell(withIdentifier: iden1) as? ShowCell1
        let cell2 = tableView.dequeueReusableCell(withIdentifier: iden2) as? ShowCell2
        let cell3 = tableView.dequeueReusableCell(withIdentifier: iden3) as? ShowCell3
        
        let model = (self.mutaArray[indexPath.row])
        
        if model.cellType == CellType.onePic {
          
            cell1?.model = model
            
            cell1?.backgroundColor = UIColor.white
            
            return cell1!
            
        }else if model.cellType == CellType.noPic{
            
            cell2?.model = model
            
            cell2?.backgroundColor = UIColor.white
            
            return cell2!
            
        }else {
            
            cell3?.model = model
            cell3?.backgroundColor = UIColor.white
            
            return cell3!
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int{
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return mutaArray.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let model = (self.mutaArray[indexPath.row])
        
        if model.cellType == CellType.onePic {
            
            return 150
            
        }else if model.cellType == CellType.noPic{
            
           return 120
            
        }else {
            
           
          return 150
            
        }
        
        
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        tableView.deselectRow(at: indexPath, animated: true)
        
        let model = (self.mutaArray[indexPath.row])
        
        let detailVC = HomeDetailViewController()
        detailVC.model = model
        self.navigationController?.pushViewController(detailVC, animated: true)
        
    }
    
    
}

//MARK: -请求网络
extension HomeViewController{
    
    @objc private func loadData() -> Void {
        
        PKHUD.sharedHUD.contentView = PKHUDProgressView()
        PKHUD.sharedHUD.show()
       
     
        HomeViewModel.laodData(page: 1, finishBlock: { (modelsArray,isHaveNext) in
            
            self.mutaArray = modelsArray
            
            self.tableView?.reloadData()
            
            self.tableView?.mj_header.endRefreshing(completionBlock: {
                
                print("刷新完成")
               
            })
            
            self.tableView?.mj_footer.isHidden = !isHaveNext
            
           PKHUD.sharedHUD.hide(true)
            PKHUD.sharedHUD.contentView = PKHUDSuccessView()
            PKHUD.sharedHUD.show()
            PKHUD.sharedHUD.hide(afterDelay: 0)
            
        }) { (error) in
            
            PKHUD.sharedHUD.hide(true)
            PKHUD.sharedHUD.contentView = PKHUDErrorView()
            PKHUD.sharedHUD.show()
            PKHUD.sharedHUD.hide(afterDelay: 0)
            
        }
    }
    
    
    @objc private func laodNextPage() -> Void {
        
        
        
        
        HomeViewModel.laodData(page: self.page, finishBlock: { (modelsArray,isHaveNext) in
            
            self.mutaArray += modelsArray
            
            self.tableView?.reloadData()
            
            self.tableView?.mj_footer.endRefreshing(completionBlock: {
                
                print("上拉刷新完成")
                
            })
            
            self.tableView?.mj_footer.isHidden = !isHaveNext
            PKHUD.sharedHUD.contentView = PKHUDSuccessView()
            PKHUD.sharedHUD.show()
            PKHUD.sharedHUD.hide(afterDelay: 0)
            
        }) { (error) in
            
            self.page -= 1
            PKHUD.sharedHUD.contentView = PKHUDErrorView()
            PKHUD.sharedHUD.show()
            PKHUD.sharedHUD.hide(afterDelay: 0)
            
        }
    }
}

// MARK: MJRefresh刷新
extension HomeViewController{
    
    func setupMJRefresh() -> Void {
      
        
        self.tableView?.mj_header = MJRefreshNormalHeader()
        self.tableView?.mj_header.setRefreshingTarget(self, refreshingAction: #selector(loadData))
        self.tableView?.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
          
            //print("上拉刷新操作")
            
            self.page += 1
            
            self.laodNextPage()
            
        })
        self.tableView?.mj_footer.isHidden = true
        
    }

}




